package pers.cj.pdos.utils;

import pers.cj.pdos.entity.BusinessSet;
import pers.cj.pdos.entity.GoodsSn;
import pers.cj.pdos.entity.OrderRule;
import pers.cj.pdos.vo.GoodsVo;
import pers.cj.pdos.vo.UserVo;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

public class PdosUtils {

    /**
     * 从数据库返回的map取出YY-MM-DD格式的日期字符串
     * @param map
     * @param key
     * @return
     */
    public static String genDateFromMap(Map map,String key){
        Object date = map.get(key);
        if (date instanceof Date) {
            return DateUtils.getDate((Date) date,DateUtils.YYYY_MM_DD);
        }

        String str = (String) date;
        if (Utils.isEmpty(str)){
            return null;
        }
        if (str.length() < 10) {
            return str;
        }
        return str.substring(0,10);
    }

    public static BigDecimal genValueFromMap(Map map, String key){
        return new BigDecimal(map.get(key).toString());
    }

    /**
     * 计算环比
     * @param nowData 现在的数据
     * @param lastData 曾经的数据
     * @return 环比
     */
    public static BigDecimal calcChainRatio(BigDecimal nowData, BigDecimal lastData){
        if(nowData == null || lastData==null) {
            return null;
        }

        if (lastData.compareTo(new BigDecimal(0))==0) {
            if (nowData.compareTo(new BigDecimal(0))==0) {
                return new BigDecimal(0);
            } else if (nowData.compareTo(new BigDecimal(0))==-1){
                //今日是0，则
                return new BigDecimal(-100);
            }
            return new BigDecimal(100);
        }

        BigDecimal ratio = nowData.subtract(lastData).multiply(new BigDecimal(100)).divide(lastData, 4, RoundingMode.HALF_UP);
        if (ratio.compareTo(new BigDecimal(0)) == -1 && nowData.compareTo(lastData) == 1) {
            // 当环比小于0(曾经的数据为0时)，且今日数据大于曾经的数据
            ratio = ratio.negate();
        }
        return ratio;
    }

    /**
     * 比较日期的差距
     * @param date1
     * @param date2
     * @return
     *          -1:入参错误
     *          1 年份差距
     *          2 月份差距
     *          3 天数差距
     */
    public static int calcDateDiffFlag(String date1, String date2){
        if (Utils.isEmpty(date1) || Utils.isEmpty(date2)) {
            return -1;
        }

        Calendar calendarStart = Calendar.getInstance();
        calendarStart.setTime(Utils.genDate(date1));

        Calendar calendarEnd = Calendar.getInstance();
        calendarEnd.setTime(Utils.genDate(date2));

        int startYear = calendarStart.get(Calendar.YEAR);
        int startMonth = calendarStart.get(Calendar.MONTH);
        int startDate = calendarStart.get(Calendar.DATE);

        int endYear = calendarEnd.get(Calendar.YEAR);
        int endMonth = calendarEnd.get(Calendar.MONTH);
        int endDate = calendarEnd.get(Calendar.DATE);
        if (startYear != endYear) {
            return 1;
        }else if (startMonth != endMonth) {
            return 2;
        } else {
            return 3;
        }
    }

    /**
     * 根据日期获取期间间隔的内容
     * @param date1
     * @param date2
     * @return map key:chat x轴内容
     */
    public static Map<String,Object> calcDateDiffMap(String date1, String date2, BusinessSet businessSet) {
        Map<String,Object> map = new LinkedHashMap<>();
        if (Utils.isEmpty(date1) || Utils.isEmpty(date2)) {
            return map;
        }

        String zero = PdosUtils.getPrice(new BigDecimal(0), businessSet);

        Calendar calendarStart = Calendar.getInstance();
        calendarStart.setTime(Utils.genDate(date1));

        Calendar calendarEnd = Calendar.getInstance();
        calendarEnd.setTime(Utils.genDate(date2));

        int startYear = calendarStart.get(Calendar.YEAR);
        int startMonth = calendarStart.get(Calendar.MONTH);
        int startDate = calendarStart.get(Calendar.DATE);

        int endYear = calendarEnd.get(Calendar.YEAR);
        int endMonth = calendarEnd.get(Calendar.MONTH);
        int endDate = calendarEnd.get(Calendar.DATE);

        if (startYear != endYear) {
            calendarStart.add(Calendar.YEAR, -1);
            for (int i=0; i <= endYear-startYear; i++) {
                calendarStart.add(Calendar.YEAR, 1);
                map.put(calendarStart.get(Calendar.YEAR)+"年", zero);
            }
        } else if (startMonth != endMonth) {
            calendarStart.add(Calendar.MONTH, -1);
            for (int i=0; i <= endMonth-startMonth; i++) {
                calendarStart.add(Calendar.MONTH, 1);
                map.put((calendarStart.get(Calendar.MONTH) + 1) + "月", zero);
            }
        } else if (startDate!=endDate){
            calendarStart.add(Calendar.DATE, -1);
            for (int i=0; i <= endDate-startDate; i++) {
                calendarStart.add(Calendar.DATE, 1);
                map.put(calendarStart.get(Calendar.DAY_OF_MONTH)+"日", zero);
            }
        } else {
            calendarStart.add(Calendar.DATE, -7);
            for (int i=0; i <= 6; i++) {
                calendarStart.add(Calendar.DATE, 1);
                map.put(calendarStart.get(Calendar.DAY_OF_MONTH)+"日", zero);
            }
        }

        return map;
    }

    public static long genLong(Long num){
        return num==null ? 0 : num;
    }

    public static String getPrice(BigDecimal price, BusinessSet businessSet) {
        return price.setScale(businessSet.getPricePoint(), RoundingMode.HALF_UP).toString();
    }

    public static String getNumber(BigDecimal number, BusinessSet businessSet) {
        return number.intValue() ==  number.doubleValue() ? number.intValue()+"":number.setScale(businessSet.getPricePoint(), RoundingMode.HALF_UP).toString();
    }

    /**
     * 获取单号
     * @param orderRule
     * @return
     */
    public static String getNo(OrderRule orderRule){
        StringBuilder sb = new StringBuilder();
        sb.append(orderRule.getPrefix());
        sb.append(DateUtils.getDate(new Date(), DateUtils.YYYYMMDD));
        sb.append(String.format("%0"+orderRule.getNum()+"d",orderRule.getCurrent()));
        orderRule.setCurrent(orderRule.getCurrent()+1);
        return sb.toString();
    }

    /**
     * 允许负库存销售
     * @return true启用 false停用
     */
    public static boolean negativeSale(BusinessSet businessSet){
        if (businessSet.getNegative() == null || !businessSet.getNegative()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 是否启用出入库管理
     * @return true启用 false停用
     */
    public static boolean houseInOut(BusinessSet businessSet){
        if (businessSet.getHouseInOut() == null || !businessSet.getHouseInOut()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 是否启用销售税率
     * @return true启用 false停用
     */
    public static boolean saleTaxRateFlag(BusinessSet businessSet){
        //为开启销售税率标志，或者销售税率为空
        if (businessSet.getSaleTaxRateFlag() == null || !businessSet.getSaleTaxRateFlag()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 是否启用出入库管理
     * @return true启用 false停用
     */
    public static boolean getBoolean(Boolean flag){
        if (flag == null || !flag) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获取可以查看他人供应商的storeId
     * @param userVo
     * @param storeId
     * @return
     */
    public static String getProviderStoreId(UserVo userVo,String storeId) {
        // 分店人员，可以看到本店所有的供应商
        if (!userVo.getStore().getSys() ) {
            storeId = userVo.getStoreId();
        }

        return storeId;
    }

    /**
     * 获取可以查看他人客户的storeId
     * @param userVo
     * @param storeId
     * @return
     */
    public static String getViewCustomStoreId(UserVo userVo,String storeId) {
        // 分店人员，可以看到本店所有的客户
        if (!userVo.getStore().getSys()) {
            storeId = userVo.getStoreId();
        }

        return storeId;
    }

    /**
     * 获取可以查看其他门店的storeId
     * @param userVo
     * @param storeId
     * @return
     */
    public static String getViewHouseStoreId(UserVo userVo,String storeId) {
        // 登录用户不是总部员工 且不能查看其他仓库， 则只能查看本门店的仓库
        if (!userVo.getStore().getSys()) {
            storeId = userVo.getStoreId();
        }

        return storeId;
    }

    /**
     * 获取可以查看他人单据的userId
     * @param userVo
     * @param userId
     * @return
     */
    public static String getViewOrderUserId(UserVo userVo,String userId) {
        // 不能查看他人单据，则只能查看自己的单据
        if (!PdosUtils.getBoolean(userVo.getViewOtherOrder())) {
            userId = userVo.getId();
        }

        return userId;
    }

    /**
     * 获取可以查看他人单据的storeId
     * @param userVo
     * @param storeId
     * @return
     */
    public static String getViewOrderStoreId(UserVo userVo, String storeId) {
        // 总部员工，且可以查看他人单据， 则可以查看所有人的单据

        // 可以查看他人单据，且登录用户不是总部员工 ， 则只能查看本门店数据
        if (getBoolean(userVo.getViewOtherOrder()) && !userVo.getStore().getSys()){
            storeId = userVo.getStoreId();
        }

        return storeId;
    }

    /**
     * 获取除单据以外（库存查询、序列号查询等，只用storeId来匹配登录员工可以查看的数据）的storeId，
     * @param userVo
     * @param storeId
     * @return
     */
    public static String getViewOtherStoreId(UserVo userVo, String storeId) {
        // 总部员工，且可以查看他人单据， 则可以查看所有人的单据

        // 可以查看他人单据，且登录用户不是总部员工 ， 则只能查看本门店数据
        if (!userVo.getStore().getSys()){
            storeId = userVo.getStoreId();
        }

        return storeId;
    }

    /**
     * 销售税率
     * @return
     */
    public static BigDecimal saleTaxRate(BusinessSet businessSet){
        if (businessSet.getSaleTaxRate()==null) {
            return new BigDecimal(0);
        } else {
            return businessSet.getSaleTaxRate().divide(new BigDecimal(100));
        }
    }


    /**
     * 是否启用进货税率
     * @return true启用 false停用
     */
    public static boolean inTaxRateFlag(BusinessSet businessSet){
        if (businessSet.getInTaxRateFlag() == null || !businessSet.getInTaxRateFlag()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 进货税率
     * @return
     */
    public static BigDecimal inTaxRate(BusinessSet businessSet){
        if (businessSet.getInTaxRate()==null) {
            return new BigDecimal(0);
        } else {
            return businessSet.getInTaxRate().divide(new BigDecimal(100));
        }
    }


    /**
     * 从xx商品的list中提取goodsSn的list
     * @param list
     * @return
     */
    public static List<GoodsSn> genGoodsSnList(List list) {
        List<GoodsSn> goodsSnList = new ArrayList<>();
        if (Utils.isEmpty(list)) {
            return goodsSnList;
        }


        for (Object entity : list) {
            GoodsVo goodsVo = (GoodsVo) ReflectionUtils.getFieldValue(entity, "goodsVo");
            if (goodsVo==null || Utils.isEmpty(goodsVo.getGoodsSnList())) {
                continue;
            }

            for (GoodsSn goodsSn : goodsVo.getGoodsSnList()) {
                goodsSnList.add(goodsSn);
            }
        }
        return goodsSnList;
    }
}
